package com.hechao.controller;

import com.hechao.code.Code;
import com.hechao.domain.User;
import com.hechao.service.UserService;
import com.hechao.result.Result;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin  //跨域
public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("/All")
    public Result selectAll(){
        List<User> userList = userService.queryAll();
        return new Result(userList);
    }


    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id){
        Boolean deleteById = userService.deleteById(id);
        if (deleteById){
            //删除成功
            return new Result("删除成功",Code.DELETE_OK);
        }
        return new Result("删除失败",Code.DELETE_ERR);
    }

    @PutMapping
    public Result update(@RequestBody User user){
        System.out.println("页面需要修改的数据："+user);
        Boolean update = userService.update(user);
        if (update){
            //修改成功
            return new Result("修改成功",Code.UPDATE_OK,true);
        }
        return new Result("修改失败",Code.UPDATE_ERR,false);
    }

    @PostMapping
    public Result insert(@RequestBody User user){
        System.out.println("要添加的数据"+user);
        int i = userService.insert(user);
      if (i==1){
          //插入成功
          return new Result("插入成功",Code.INSERT_OK,true);
      }
        return new Result("插入失败",Code.INSERT_ERR,false);
    }



    //根据用户名和密码登录
    @PostMapping("/loginByUsernameAndPwd")
    public Result loginByUsernameAndPwd(@RequestBody User user){
        System.out.println("页面数据"+user);
        User login = userService.loginByUsernameAndPwd(user.getUsername(), user.getPassword());
        if (login==null){
            //查询为空，登录失败
            return new Result("登录失败", Code.LOGIN_ERR);
        }
        return new Result("登录成功",Code.LOGIN_OK,login);
    }





}
